﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zzcore.Model;
using Masuit.Tools.Security;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

namespace Zzcore.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ILogger<UserController> _logger;
        private readonly IFreeSql _fsql;
        public UserController(ILogger<UserController> logger, IFreeSql fsql){
            this._logger = logger;
            this._fsql = fsql;
        }

        [HttpPost]
        public async Task<Dictionary<string, Object>> Login([FromForm] User loginUser)
        {
            User user = await _fsql.Select<User>().Where(u => u.Username == loginUser.Username).ToOneAsync();

            if (user == null) {
                return RenderJson(status: "failed", message: "该用户不存在", code: 1001, data: user);
            }

            if (!user.Password.Equals(loginUser.Password))
            {
                return RenderJson(status: "failed", message: "密码错误", code: 1002, data: user);
            }

            if (user.Status == -1)
            {
                return RenderJson(status: "failed", message: "该账号已禁用", code: 1002, data: user);
            }

            await _fsql.Update<User>(user.Id).Set(u => u.Visits + 1).ExecuteAffrowsAsync();

            user.Rids = await _fsql.Select<RoleUser>().Where(ru => ru.Uid == user.Id).ToListAsync(ru => ru.Rid);
            JObject data = JObject.FromObject(user);

            Department department = await _fsql.Select<Department>().Where(d => d.Id == user.Did).ToOneAsync();
            data.Add("department", department == null ? null : JObject.FromObject(department));

            return RenderJson(data: data);
        }

        [NonAction]
        protected Dictionary<string, Object> RenderJson(string status = "success", string message = "成功", int code = 0, Object data = null)
        {
            Dictionary<string, Object> result = new();
            result.Add("status", status);
            result.Add("message", message);
            result.Add("code", code);
            result.Add("data", data);
            return result;
        }
    }
}
